import os
import webview
from http.server import SimpleHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import threading
import random
import time

# 自定义HTTP服务器，以支持多线程处理
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):

    pass

# 定义HTTP服务器端口
PORT =  random.randint(10000, 65535)
httpd = None
class mywebdows():
    def __init__(self):
        windows = webview.create_window('测试', f'http://localhost:{PORT}/index.html',js_api=MyApi())
        # windows.js_api_endpoint = 'MyApi'
        webview.start(debug=True)
        # 创建HTTP服务器处理函数
class MyApi():
    def close(self):
        pass
    def show_haha(self):
        return 'haha'
def start_server():
    # 假设前端文件位于当前目录下的'frontend'文件夹中
    os.chdir('frontend')
    server_address = ('', PORT)
    global httpd
    httpd = ThreadedHTTPServer(server_address, SimpleHTTPRequestHandler)
    print("Starting server...")
    httpd.serve_forever()
def stop_server():
    global httpd
    httpd.shutdown()
    httpd.server_close()
if __name__ == '__main__':
    # 启动HTTP服务器线程
    server_thread = threading.Thread(target=start_server)
    server_thread.start()
    time.sleep(1)  # 等待服务器启动
    win = mywebdows()
    print("结束代码")
    stop_server()
    server_thread.join()
    print("结束线程")